<?php

	/**
	 * json  0失败  1成功  2跳转  3弹窗   4未激活  5冻结
	 */

	namespace app\api\controller;


	use app\home\model\MemberModel;
	use core\basic\Controller;


	class MemberController extends Controller
	{
		protected $model;


		public function __construct()
		{

			$this->model = new MemberModel();


		}
		public function index()
		{

			$this->CheckUser();
			$user_id=$this->Memcache(2, session('uid'));

			$userInfo = $this->model->getUser($user_id->id);
			//当月新增会员 以及 激活会员
			$current_user = $this->model->current_user();
			$beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y')); //当月开始时间
			$endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));//当月结束时间
			foreach ($current_user as $k => $v) {
				if (strtotime($v->register_time) >= $beginThismonth && strtotime($v->register_time) <= $endThismonth) {
					$ret[$k] = $v;
				}
			}
			if ($ret) {
				if (!!$GetTree = $this->model->GetTree(object_to_array($ret), $userInfo->id)) {
					foreach ($GetTree as $k => $value) {
						if ($value['gid'] != '1') {
							$activate[$k] = $value;
						}
					}
				}
				$countData = array(
					'NewUser' => count($GetTree), //当月新增会员条数
					'activate' => count($activate), //激活会员会员
				);
			}
			$userInfo->count = $countData;
			if ($userInfo->gid == 1) {
				$data = array(
					'msg' => '账号未激活,请先联系推荐人激活！',
					'data' => $userInfo,
				);
				json(3, $data);

			} else {
				$userData = array(
					'data' => $userInfo,
				);

				json(1, $userData);
			}

		}

		/**
		 * 会员登录接口
		 */
		public function login()
		{
			$usermobile = request('usermobile', 'num', true, '手机号码');
			$password = request('password', 'var', true, '密码');
			$rpassword = request('rpassword', 'var', true, '确认密码');
			if ($password != $rpassword) {
				json(0, '确认密码不正确！');
			} else {
				$password = md5(md5($password));
			}
			$checkUsername = $this->model->login(['usermobile' => $usermobile, 'password' => $password]);

			if ($checkUsername->status == '0') {
				json(0, '账号已经锁定！');
			}
			if (!empty($checkUsername)) {
				session('uid', $checkUsername->id);

				$this->Memcache(1, $checkUsername->id, $checkUsername, $this->config('tpl_html_cache_time'));
				json(2, '登录成功 ', 'index.html');
			} else {
				json(0, '请检查账号密码是否正确！');
			}
		}


		/**
		 * 会员注册接口
		 */

		public function register()
		{
			$InviteCode = request('InviteCode', 'is_null', true, '推荐码');

			$password = request('password', 'is_null', true, '密码');
			$rpassword = request('rpassword', 'is_null', true, '确认密码');
			$usermobile = request('usermobile', 'is_null', true, '手机号码');
			$checkcode = request('checkcode', 'is_null', true, '短信验证码');
			$TradersPassword = request('TradersPassword', 'is_null', true, '交易密码');
			if (!preg_match("/^1([0-9]{9})/", $usermobile)) {
				json(0, '请填写正确的手机号!');
			}
			if ($InviteCode) {
				$CheckInviteCode = $this->model->checkUsername("(InviteCode='$InviteCode' )");
				if (!$CheckInviteCode) {
					json(0, '推荐人不存在！');
				}
			}
			$pid = object_array($CheckInviteCode);
			if ($this->model->checkUsername("(usermobile='$usermobile' )")) {
				json(0, '手机号码已存在！');
			}
			if ($password != $rpassword) {
				json(0, '确认密码不正确！');
			} else {
				$password = md5(md5($password));
			}

			if ($checkcode != $this->Memcache(2, $usermobile)['sms_mobile_code']) {
				json(0, '验证码错误!');
			}
			$ucode = get_auto_code($this->model->getLastUcode(), 1);
			$status = $this->config('register_verify') ? 0 : 1; // 默认不需要审核
			$score = $this->config('register_score') ?: 0;//会员静态积分
			$qcore = $this->config('login_score') ?: 0;//会员动态积分
			$up_integral = $this->config('up_integral') ?: 0;//会员充值积分
			$data = array(
				'ucode' => $ucode,
				'username' => $usermobile,
				'password' => $password,
				'usermobile' => $usermobile,
				'TradersPassword' => md5(md5($TradersPassword)),
				'nickname' => '',
				'InviteCode' => create_code(16),
				'headpic' => '',
				'status' => $status,
				'pid' => $pid['id'],
				'gid' => 1,
				'wxid' => '',
				'qqid' => '',
				'wbid' => '',
				'activation' => 0,
				'score' => $score, //静态钱包
				'qcore' => $qcore,//动态钱包
				'up_integral' => $up_integral,//充值积分
				'register_time' => get_datetime(),
				'login_count' => 0,
				'last_login_ip' => 0,
				'last_login_time' => 0,
			);
			// 读取字段
			if (!!$field = $this->model->getField()) {
				foreach ($field as $value) {
					$field_data = post($value->name);
					if (is_array($field_data)) { // 如果是多选等情况时转换
						$field_data = implode(',', $field_data);
					}
					$field_data = preg_replace_r('pboot:if', '', $field_data);
					if ($value->required && !$field_data) {
						json(0, $value->description . '不能为空！');
					} else {
						$data[$value->name] = $field_data;
					}
				}
			}

			// 执行注册
			if ($this->model->register($data)) {
				session('lastreg', time()); // 记录最后提交时间
				json(1, '注册成功', 'sign-in.html');

			} else {
				json(0, '会员注册失败');

			}

		}

		/**
		 * 发送短信接口
		 */
		public function send()
		{

			$usermobile = request('mobile', 'num', true, '手机号码');
			if (!preg_match("/^1([0-9]{9})/", $usermobile)) {
				json(0, '请填写正确的手机号!');
			}

			if ($this->model->checkUsername("(usermobile='$usermobile' )")) {
				json(0, '手机号码已存在！');
			}
			$memcacheInfo = $this->Memcache(2, $usermobile);//当前会员缓存信息
			$send_code = $memcacheInfo['sms_mobile_code'];

			$code = create_code(6);
			if (!empty($memcacheInfo) or $code == $send_code) {
				json(0, '验证码已经发送!请勿重复提交');
			}
			if ($this->config('sendsms_open') !== '0') {

				$smsText = "你当前验证码为:" . $code . ",3分钟有效期";
				$data = array(
					'Uid' => $this->config('Uid'),
					'Key' => $this->config('sendsms_secret_key'),
					'smsMob' => $usermobile,
					'smsText' => $smsText
				);

				if (sendsms($data) == true) {
					$code_info['last_access'] = time();
					$code_info['sms_mobile'] = $usermobile;
					$code_info['sms_mobile_code'] = $code;
					$this->Memcache(1, $usermobile, $code_info, 180);
					json(1, '验证码已发送！');
				}
			}
		}

		// 退出登录
		public function logout()
		{

			if ($this->Memcache(4,session('uid'))) {

				session('uid', '');
				json(2, '退出成功！', 'sign-in.html');
			}

		}

		/*
		 * 请求团队接口
		 */
		public function team()
		{
			$user_id = $this->Memcache(2, session('uid'))->id;
			$current_user = $this->model->current_user();

			if ($current_user) {
				$GetTree = $this->model->GetTree(object_to_array($current_user), $user_id);
				$data = array(
					'msg' => '加载成功！',
					'data' => array_to_object($GetTree)
				);
				json(1, $data);
			} else {
				json(0, '加载失败！');
			}

		}

		/*
		 * 会员激活下级接口
		 */
		public function Activation()
		{

			$pid = request('pid', 'num', true, '下级ID');//需要激活的用户ID
			$PuserInfo = $this->model->getUser($pid);//当前点击会员信息
			$user_id = $this->Memcache(2, session('uid'))->id;
			$userInof = $this->model->getUser($user_id);//当前会员信息

			if (!$PuserInfo) {
				json(0, '当前会员不存在！');
			}
			if ($PuserInfo->status == 0) {
				json(0, '会员已被锁定,请联系管理员解锁！');
			}
			if ($userInof->gid == 1) {
				json(4, '请先激活当前登录账号！');
			}
			if (!$getCurrent = model('admin.member.Activation')->getCurrent($userInof->usermobile)) {
				json(0, '激活码不足！');
			} elseif (model('admin.member.Activation')->modCurrent($getCurrent->id, ['status' => 2, 'user_id' => $PuserInfo->id, 'ues_time' => get_datetime()]) && $this->model->modUser($PuserInfo->id, ['gid' => 2])) {

				model('admin.member.Bill')->AddBill($userInof->id, 5, '激活会员为' . $PuserInfo->usermobile,4);
				json(1, '激活成功！');
			}
		}

		/*
		 * 会员激活接口
		 */
		public function ActivationUser()
		{

			$userId = request('user_id', 'num', true, '会员ID');//需要激活的用户ID
			$memcacheInfo = $this->Memcache(2, $userId);
			if (!$getCurrent = model('admin.member.Activation')->getCurrent($memcacheInfo->usermobile)) {
				json(0, '激活码不足！');
			} elseif (model('admin.member.Activation')->modCurrent($getCurrent->id, ['status' => 2, 'user_id' => $userId, 'ues_time' => get_datetime()]) && $this->model->modUser($userId, ['gid' => 2])) {
				model('admin.member.Bill')->AddBill($memcacheInfo->id, 5, '激活会员为' . $memcacheInfo->usermobile);
				json(1, '激活成功！');
			}
		}

		/*
		 * 查询当前用户 所拥有的激活码
		 */
		public function GetActivation()
		{
			$memcacheInfo = $this->Memcache(2, session('uid'));
			$havecount = model('admin.member.Activation')->GetCount(['status' => 2, 'usermobile' => $memcacheInfo->usermobile]);//查询当前会员已经使用的激活码
			$notcount = model('admin.member.Activation')->GetCount(['usermobile' => $memcacheInfo->usermobile]);//查询当前会员所有的激活码

			$data = array(
				'havecount' => $havecount,
				'notcount' => $notcount,

			);
			json(1, $data);


		}

		/**
		 * 派送激活码
		 *
		 */
		public function delivery()
		{
			$memcacheInfo = $this->Memcache(2, session('uid'));
			$Member_account = request('Member_account', 'is_null', true, '下级会员账号');//下级会员账号
			$number = request('number', 'num', true, '派送数量');//派送数量
			$TradersPassword = request('TradersPassword', 'is_null', true, '交易密码');//交易密码

			$JuniorMembers = $this->model->checkUsername(['usermobile' => $Member_account, 'pid' => $memcacheInfo->id]);
			if ($memcacheInfo->usermobile == $Member_account) {
				json(0, '操作有误！');
			}

			if (!$JuniorMembers) {
				json(0, '当前会员不存在！');
			}
			if (md5(md5($TradersPassword)) != $memcacheInfo->TradersPassword) {
				json(0, '交易密码错误');
			}
			$havecount = model('admin.member.Activation')->GetActivation(['status' => 1, 'usermobile' => $memcacheInfo->usermobile], $number);//查询当前会员未使用的激活码
			if (count($havecount) < $number) {
				json(0, '数量不足，无法派送！');
			} else {
				try {
					foreach ($havecount as $k => $value) {
						if (!!$delActivation = model('admin.member.Activation')->delActivation($value->id)) {
							continue;
						}
					}
					if ($delActivation) {
						for ($i = 0; $i < $number; $i++) {
							$check = true;
							while ($check == true) {
								$cdkey = makeCardPassword();
								$result = model('admin.member.Activation')->checkCodefind(['code' => $cdkey]);
								if (empty($result)) {
									$data['code'] = $cdkey;
									$data['status'] = 1;
									$data['add_time'] = get_datetime();
									$data['ues_time'] = '';
									$data['user_id'] = '';
									$data['source'] = $memcacheInfo->usermobile;
									$data['usermobile'] = $Member_account;
									$results = model('admin.member.Activation')->addActivation($data);
									$check = false;
								}
							}
						}
						if ($results) {
							$JunLog = '接收' . $memcacheInfo->usermobile . '转让的' . $number . '条激活码';
							$UserLog = '转让' . $number . '条激活码给' . $Member_account;
							if (!!model('admin.member.Bill')->AddBill($JuniorMembers->id, 6, $JunLog, 4) && !!model('admin.member.Bill')->AddBill($memcacheInfo->id, 4, $UserLog, 4)) {
								json(1, '派送成功');
								$this->model->commit();
							}else{
								$this->model->rollback();
								json(0, error());
							}
						}
					}
				} catch (Exception $e) {
					$this->model->rollback();
					json(0, error());
				}

			}


		}

		/**
		 * $Member_account 0 为静态 1是动态
		 */
		public function transform()
		{
			$memcacheInfo = $this->Memcache(2, session('uid'));
			$userInfo = $this->model->checkUsername(['id' => $memcacheInfo->id]);
			$Member_account = request('Member_account', 'num', true, '积分类型');//积分类型
			$number = request('number', 'int', true, '转换数量');//转换数量
			if ($number % 100 != 0) {
				json(0, '数量必须是100的倍数！');
			}
			$TradersPassword = request('TradersPassword', 'num', true, '交易密码');//交易密码
			if (md5(md5($TradersPassword)) != $memcacheInfo->TradersPassword) {
				json(0, '交易密码错误');
			}
			if ($Member_account == 0) {
				if ($userInfo->qcore < $number) {
					json(0, '静态积分不足！');
				}
				$type = '静态积分';
				$field = 'qcore';
				$genre = '2';
			} else {
				if ($userInfo->score < $number) {
					json(0, '动态积分不足！');
				}
				$type = '动态积分';
				$field = 'score';
				$genre = '3';
			}
			try {
				if ($UsersetDec= $this->model->UsersetDec(['id' => $userInfo->id], $field, $number)) {
					$JunLog = '转让' . $number . $type . '到' . $userInfo->usermobile;
					model('admin.member.Bill')->AddBill($userInfo->id, 4, $JunLog, $genre);
				}
				if ($UsersetInc=$this->model->UsersetInc(['id' => $userInfo->id], 'up_integral', $number)) {
					$JunLog = '接收用户' . $userInfo->usermobile . '转让的' . $number . $type . '到充值积分';
					model('admin.member.Bill')->AddBill($userInfo->id, 6, $JunLog, 1);
				}
				if($UsersetDec && $UsersetInc){
					json(1, '转换成功！');
					$this->model->commit();
				}else{
					$this->model->rollback();
					json(0, error());
				}

			} catch (Exception $e) {

				$this->model->rollback();
				json(0, error());
			}
		}

		/**
		 * 会员提现
		 */
		public function withdraw()
		{
			$number = request('number', 'num', true, '提现金额');//提现金额
			$TradersPassword = request('TradersPassword', 'num', true, '交易密码');//交易密码
			$arrival_amount = request('arrival_amount', 'num', true, '到账金额');//到账金额
			$bank = request('bank', 'num', true, '银行卡号');//银行卡号
			$sxf = request('sxf', 'num', false, '手续费');//手续费

			$memcacheInfo = $this->Memcache(2, session('uid'));
			$userInfo = $this->model->checkUsername(['id' => $memcacheInfo->id]);
			$this->config('minQuota');
			if (model('admin.member.Member')->Getwithdraw(['user_id' => $userInfo->id, 'status' => 1])) {
				json(0, '提现申请正在审核中');
			}
			if ($userInfo->up_integral < $number) {
				json(0, '额度不足');
			}
			if ($number < $this->config('minQuota')) {
				json(0, '最小提现额度' . $this->config('minQuota'));
			}

			if ($number % $this->config('multiple') != 0) {
				json(0, '数量必须是' . $this->config('multiple') . '的倍数！');
			}
						if (md5(md5($TradersPassword)) != $userInfo->TradersPassword) {
				json(0, '交易密码错误');
			}

			if ($this->config('sxf') != 0) {
				if ($sxf != $this->config('sxf')) {
					json(0, '操作失败！');
				}
				$sxf = $sxf;
				$amount = $number - $number * $this->config('sxf');
			} else {
				$sxf = '0';
				$amount = $number;
			}
			if ($amount != $arrival_amount) {
				json(0, '操作失败！');
			}

			try {

				$JunLog = '冻结' . $userInfo->usermobile . '申请提现的' . $number . '充值积分实际到账'.$arrival_amount;
				$Bill = model('admin.member.Bill')->AddBill($userInfo->id, 7, $JunLog, 1);
				$frostArr = array(
					'user_id' => $userInfo->id,
					'money' => $number,
					'frost_type' => 1,
					'frost_time' => get_datetime(),
					'is_frost' => 2,
					'thawing_time' => 0,
				);
				$frost = model('admin.member.Member')->Addfrost($frostArr);
				$data = array(
					'user_id' => $userInfo->id,
					'bank_id' => $bank,
					'quota' => $number,
					'sxf' => $sxf,
					'amount' => $amount,
					'status' => 1,
					'add_time' => get_datetime(),
					'audit_time' => '',
					'frost_id' => $frost,
				);
				if ($frost && $Bill && $this->model->UsersetDec(['id' => $userInfo->id], 'up_integral', $number) && model('admin.member.Member')->Addwithdraw($data)) {
					json(1, '提交成功，等待审核！');
					$this->model->commit();
				} else {
					$this->model->rollback();
					json(0, error());
				}
			} catch (Exception $e) {
				$this->model->rollback();
				json(0, error());
			}

		}

		/**
		 * 添加银行卡
		 */
		public function Userbank()
		{
			$account_name = request('account_name', 'vars', true, '开户名');//开户名
			$Card = request('Card', 'bank', true, '开户卡号');//开户卡号
			$Bank_deposit = request('Bank_deposit', 'vars', true, '开户行');//开户行
			$memcacheInfo = $this->Memcache(2, session('uid'));
			$userInfo = model('admin.member.Member')->checkMember(['id' => $memcacheInfo->id]);
			if ($userInfo->gid == 1) {
				json(0, '账号暂时未激活,无法添加！');
			}
			if (count($this->model->UserbankList($userInfo->id)) >= 3) {
				json(0, '每个用户最多添加三个卡号');
			}

			if ($this->model->UserbankInfo(['Card' => $Card])) {
				json(0, '卡号已经存在');
			}
			$data = array(
				'account_name' => $account_name,
				'Card' => $Card,
				'Bank_deposit' => $Bank_deposit,
				'user_id' => $userInfo->id,
				'add_time' => get_datetime()
			);
			if (!!$field = $this->model->addUserbank($data)) {
				json(1, '添加成功');
			}

		}

		/**
		 * 获取当前用户银行卡
		 */
		public function UserbankList()
		{
			$list = get('list');


			$userInfo = $this->Memcache(2, session('uid'));

			$field = $this->model->UserbankList($userInfo->id);
			$arr = array();
			$i = 0;
			$fieldarr = array();
			foreach ($field as $k => $v) {
				$arr[$i]['id'] = $v->id;
				$arr[$i]['value'] = $v->Bank_deposit . formatBankCardNo($v->Card);
				$i++;
				if ($list == 1) {
					$fieldarr[$k]['Card'] = formatBankCardNo($v->Card);
					$fieldarr[$k]['account_name'] = $v->account_name;
					$fieldarr[$k]['Bank_deposit'] = $v->Bank_deposit;
					$fieldarr[$k]['id'] = $v->id;
				}
			}

			$data = [
				'field' => $field,
				'data' => $arr
			];
			if ($list == 1) {
				$data['data'] = $fieldarr;
			}
			json(1, $data);
		}

		public function DelUserbank()
		{
			$bankId = request('bid', 'is_null', true, '卡号ID');//开户名
			if (!!$this->model->DelUserbank($bankId)) {
				json(1, '删除成功');
			} else {
				json(0, '删除成功');
			}

		}

	}

